package com.ruigi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruigi.Dto.SetmealDto;
import com.ruigi.Exception.Customexception;
import com.ruigi.mapper.Setmealmapper;
import com.ruigi.pojo.Setmeal;
import com.ruigi.pojo.SetmealDish;
import com.ruigi.service.SetmealDishservice;
import com.ruigi.service.Setmealservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class Setmealimpl extends ServiceImpl<Setmealmapper, Setmeal> implements Setmealservice {
    @Autowired
    private SetmealDishservice setmealDishservice;


    @Transactional
    @Override
    public void savemealdish(SetmealDto setmealDto) {
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        List<SetmealDish> collect = setmealDishes.stream().map(s -> {
            s.setSetmealId(setmealDto.getId());
            return s;
        }).collect(Collectors.toList());

        setmealDishservice.saveBatch(collect);


    }

    @Override
    public void deleteById(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, ids);
        queryWrapper.eq(Setmeal::getStatus, 1);
        int count = this.count(queryWrapper);
        if (count > 0) {
            throw new Customexception("没有停售不能删除");
        }
        this.removeByIds(ids);

        //删除关联数据
        LambdaQueryWrapper<SetmealDish> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.in(SetmealDish::getSetmealId, ids);


        setmealDishservice.remove(queryWrapper2);

    }

    @Override
    public void setmealupdate(SetmealDto setmealDto) {
        this.updateById(setmealDto);
        Long id = setmealDto.getId();
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.eq(SetmealDish::getSetmealId, id);
        setmealDishservice.remove(setmealDishLambdaQueryWrapper);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        List<SetmealDish> collect = setmealDishes.stream().map(
                s -> {
                    s.setSetmealId(setmealDto.getId());
                    return s;
                }
        ).collect(Collectors.toList());
        setmealDishservice.saveBatch(collect);

    }
}
